package com.etrans.web.gps.business.areaTask.timer;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.etrans.web.gps.business.areaTask.domain.AreaAnalyzesVo;
import com.etrans.web.gps.business.areaTask.domain.OrganzationVO;
import com.etrans.web.gps.business.areaTask.service.AreaSendMessageService;
import com.etrans.web.gps.business.system.service.SystemService;
import com.etrans.web.gps.common.SendMessageRecord;
import com.etrans.web.gps.util.DateUtil;
import com.etrans.web.gps.util.message.SMSUtil;

public class AreaSendMessage {
	
	private static final Logger log = LoggerFactory.getLogger(AreaSendMessage.class);
	
	@Autowired
	private AreaSendMessageService areaSendMessageService;
	
	@Autowired
	private SystemService system;

	/**
	 * 每周定时短信发送
	 */
	public void areaSendMessageWeek() {
		try {
			// 获取当前日期的前一周
			Date  lastDay = DateUtil.getPreviousDayDate(7);
			int weekNum = DateUtil.getWeekNum(lastDay);
			int year = Integer.valueOf(DateUtil.getDateToString(lastDay, "yyyy"));
			Map<String,Object> lastWeek = DateUtil.getYearAndWeekByDate(year,weekNum);
			Date lastMonday = DateUtil.getStringToDate(String.valueOf(lastWeek.get("Monday")));
			Date lastSunday = DateUtil.getStringToDate(String.valueOf(lastWeek.get("Sunday")));
			String week =  weekNum < 10 ? "0" + weekNum : ""+weekNum;
			String msgTime = "(" + DateUtil.getDateToString(lastMonday, "yyyy-MM-dd")  
							 + "-"+ DateUtil.getDateToString(lastSunday, "yyyy-MM-dd") + ")";
			
			long curr = System.currentTimeMillis();
			log.info("区域周考核定时通知启动"+msgTime);
			// 查询所有的业户
			HashMap<String, Object> param=new HashMap<>();
			List<OrganzationVO> list = areaSendMessageService.queryAllAreaList(param);
			List<AreaAnalyzesVo> areaList = areaSendMessageService.queryAreaAnalyzesWeek(DateUtil.getDateToString(lastMonday, "yyMMdd"));
			boolean flag = true;
			sendSMS(list,areaList,msgTime,year+"年 第",week);
			areaSendMessageService.sendMail(list,areaList,msgTime,String.valueOf(year),week,"week",DateUtil.getDateToString(lastMonday, "yyMMdd"),flag);
			log.info("区域周考核定时通知完成:历时"+ String.valueOf(System.currentTimeMillis()-curr)+"秒");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 每月定时短信发送
	 */
	public void areaSendMessageMonth() {
		try {
			String previousMonth =DateUtil.getDateToString(DateUtil.getPreviousMonthDate(0),"yyMM");
			String msgTime = "月 ("+previousMonth.substring(2,4)+"月)区域月考核统计";
			String year=DateUtil.getDateToString(new Date(), "yyyy")+"年";
			String month=previousMonth.substring(2,4)+"";
			long curr = System.currentTimeMillis();
			log.info("区域月考核定时通知启动"+msgTime);
			// 查询所有的业户
			HashMap<String, Object> param=new HashMap<>();
			List<OrganzationVO> list = areaSendMessageService.queryAllAreaList(param);
			List<AreaAnalyzesVo> areaList = areaSendMessageService.queryAreaAnalyzesMonth(previousMonth);
			boolean flag = true;
			sendSMS(list,areaList,msgTime,year,month);
			areaSendMessageService.sendMail(list,areaList,"区域月考核统计",year,month,"month",previousMonth,flag);
			log.info("区域月考核定时通知完成:历时"+ String.valueOf(System.currentTimeMillis()-curr)+"秒");
		} catch (Exception e) {
			e.printStackTrace();
			log.info("区域月考核发送短信失败:"+e.getMessage());
		}
	}

	private void sendSMS(List<OrganzationVO> list, List<AreaAnalyzesVo> areaList, String msgTime, String year, String week) {
		for (AreaAnalyzesVo areaAnalyzes : areaList) {
			for (OrganzationVO organzation : list) {
				if(organzation.getArea_id().equals(areaAnalyzes.getArea_id())){
					Integer enable_sms = organzation.getEnable_sms();
					if(enable_sms != null && enable_sms == 1){
						if(organzation.getContacts_number()!=null && !"".equals(organzation.getContacts_number())){
							//获取联系人和手机号
							String contacts = organzation.getContacts();
							String email = organzation.getEmail();
							String contacts_number = organzation.getContacts_number();
							String sendMessage = getSendFormat(contacts,msgTime,areaAnalyzes,year,week);
							String status = SMSUtil.mt(contacts_number, sendMessage, "", "", "");
							if(status != null && !"0".equals(status)){
								SendMessageRecord smr = new SendMessageRecord();
								smr.set_id(new ObjectId());
								smr.setEmail(email);
								smr.setPhone(contacts_number);
								smr.setTips_time(new Date());
								smr.setTips_type(0);
								smr.setTarget_type(3);
								smr.setTarget_name(contacts);
								smr.setContent(sendMessage);
								areaSendMessageService.saveMessage(smr);
							}
						}
					}
				}
			}
		}
	}
/*
	public void sendMail(List<OrganzationVO> list, List<AreaAnalyzesVo> areaList, String msgTime, String year, String timeType
			,String queryType,String queryTime) {
		try {
		DecimalFormat dft = new DecimalFormat("0.00");
		for (AreaAnalyzesVo areaAnalyzes : areaList) {
			for (OrganzationVO organzation : list) {
				if(organzation.getArea_id().equals(areaAnalyzes.getArea_id())){
					Integer enable_email = organzation.getEnable_email();
					if(enable_email != null && enable_email == 1){
						if(organzation.getEmail()!=null && !"".equals(organzation.getEmail())){
							List<AreaAnalyzesVo> areaAnalyzesList=areaSendMessageService.getAreaAnalyzesList(organzation.getArea_id(),areaList);
							//获取联系人和手机号
							String contacts = organzation.getContacts();
							String email = organzation.getEmail();
							String contact_number = organzation.getContacts_number();
							//String sendMessage = getSendFormat(contacts,msgTime,areaAnalyzes,year,timeType);
							
							List<AreaAnalyzesVo> subList = new ArrayList<>();
							if(areaAnalyzesList.size()>10){
								for(int i=0;i<10;i++ ){
									subList.add(areaAnalyzesList.get(i));
								}
								for (AreaAnalyzesVo vo : areaAnalyzesList) {
									if(vo.getArea_id()==organzation.getArea_id()){
										if(!subList.contains(vo)){
											subList.add(vo);
										}
									}
								}
							}else{
								subList=areaAnalyzesList;
							}
							MailInfo info = new MailInfo();
						    info.setToAddress(email);
						    info.setSubject("贵州政府平台区域考核统计");
						        
						    //发送html格式
						    info.setFileName("emailMsgTemplate.html");
					        Map<String,Object> model = new HashMap<String,Object>();
							
					        model.put("contacts",organzation.getContacts());
					        model.put("year",year);
					        model.put("timeType", timeType);
					        model.put("detail",msgTime);
					        model.put("order",areaAnalyzes.getRanking());
					        model.put("vehicleCount",areaAnalyzes.getVehicle_count());
					        model.put("vehicleNetCount",areaAnalyzes.getVehicle_access_count());
					        model.put("enterpriseCount",areaAnalyzes.getEnterprise_count());
					        double dealRate = areaAnalyzes.getAlarm_count() > 0 && areaAnalyzes.getAlarm_processed() > 0 ?
					        		areaAnalyzes.getAlarm_processed()/areaAnalyzes.getAlarm_count() : 0 ;
					        model.put("dealRate",dft.format(dealRate*100)+"%");
					        model.put("pic", config.image_path);
					        model.put("tableTitle", "区域考核");
					        StringBuffer platStr = new StringBuffer();
					        for(int i=0;i<subList.size();i++){
					        	platStr.append("<tr>");
					        	//"排名:"
					        	platStr.append("<td>"+subList.get(i).getRanking()+"</td>");
					        	//"得分:"
					        	platStr.append("<td>"+subList.get(i).getScore()+"</td>");
					        	//名称
					        	platStr.append("<td>"+subList.get(i).getArea_name()+"</td>");
								//"车辆入网率:"
								platStr.append("<td>"+dft.format(subList.get(i).getVehicle_access_rate())+"</td>");
								//"车辆上线率:"
								platStr.append("<td>"+dft.format(subList.get(i).getVehicle_online_rate())+"</td>");
								//"在岗率:"
								platStr.append("<td>"+subList.get(i).getReply_rate()+"</td>");
								//"轨迹完整率:"
								platStr.append("<td>"+dft.format(subList.get(i).getTrack_complete_rate())+"</td>");
								//"数据合格率:"
								int trackNum = subList.get(i).getTrack_normal()+subList.get(i).getException_track_count();
								platStr.append("<td>"+(trackNum <= 0 ? 0.00 :dft.format(subList.get(i).getTrack_normal()/trackNum))+"</td>");
								platStr.append("</tr>");
					        }
					        //详细列表
					        String tableHead = " <tr><th>排名</th><th>得分</th><th>区域名称</th>" + 
					        		"<th>车辆入网率(%)</th><th>车辆上线率(%)</th><th>轨迹完整率(%)</th><th>在岗率(%)</th><th>数据合格率(%)</th></tr>";
					        model.put("tableHead",tableHead);
					        model.put("resultList",platStr);
					        //  true 发送成功 false 失败
							
							boolean status = MailSendUtil.sendHtmlMail(info, model);
							
					        if(status){
					        	SendMessageRecord smr = new SendMessageRecord();
					        	smr.set_id(new ObjectId());
					        	smr.setEmail(email);
					        	smr.setPhone(contact_number);
					        	smr.setTips_time(new Date());
					        	smr.setTips_type(1);
					        	smr.setTarget_type(3);
					        	smr.setTarget_name(contacts);
					        	smr.setContent(config.system_path+"/area/areaAnalyzes.html?areaId="+ organzation.getArea_id() +
										"&year=" + year + "&timeType="+ timeType + "&detail=" + msgTime +
										"&queryType=" + queryType + "&queryTime=" + queryTime);
					        	areaSendMessageService.saveMessage(smr);
					        	}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/
	

	/**
	 * 提取信息，转化车发送格式
	 * @param contacts 联系人
	 * @param msgTime 信息的统计时间
	 * @param week 
	 * @param year 
	 * @param platformAna 
	 * @return
	 */
	public String getSendFormat(String contacts,String msgTime,AreaAnalyzesVo vo, String year, String timeType) {
		DecimalFormat dft = new DecimalFormat("0.00");
		StringBuffer stb = new StringBuffer();
		stb.append("尊敬的"+contacts+"先生：以下信息为"+system.getAreaName()+year+timeType+msgTime+":\n");
		stb.append("区域名称："+vo.getArea_name()+",\t");
		stb.append("得分："+vo.getScore()+",\t");
		stb.append("排名："+vo.getRanking()+",\t");
		stb.append("车辆入网率："+dft.format(vo.getVehicle_access_rate())+"%,\t");
		stb.append("车辆上线率："+dft.format(vo.getVehicle_online_rate())+"%,\t");
		stb.append("在岗率："+dft.format(vo.getReply_rate())+"%,\t");
		stb.append("轨迹完整率："+dft.format(vo.getTrack_complete_rate())+"%,\t");
		int trackNum = vo.getTrack_normal()+vo.getException_track_count();
		stb.append("数据合格率："+(trackNum <= 0 ? 0 :dft.format(vo.getTrack_normal()/trackNum))+"%。\t");
		return stb.toString();
	}
	

	/**
	 * 提取信息，转化车发送格式
	 * @param contacts 联系人
	 * @param msgTime 信息的统计时间
	 * @param platformAna 
	 * @return
	 */
	public String getSendFormat(String contacts,String msgTime,Integer areaId,List<AreaAnalyzesVo> areaList) {
		DecimalFormat dft = new DecimalFormat("0.00");
		StringBuffer stb = new StringBuffer();
		stb.append("尊敬的"+contacts+"先生：以下信息为"+system.getAreaName()+msgTime+":\n");
		stb.append("区域名称\t得分\t排名\t车辆入网率\t车辆上线率\t在岗率\t轨迹完整率\t数据合格率\n");
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("FullID", String.format("%08d",areaId));
		List<HashMap<String,Object>> list = areaSendMessageService.queryAreaTree(param);
		for (HashMap<String, Object> hashMap : list) {
			String id=(Long) hashMap.get("ID")+"";
			for (AreaAnalyzesVo vo : areaList) {
				if(id.equals(vo.getArea_id()+"")){
					//"	区域："
					stb.append(vo.getArea_name()+"\t\t");
					//"得分："
					stb.append(vo.getScore()+"\t");
					//"排名："
					stb.append(vo.getRanking()+"\t");
					//"车辆入网率："
					stb.append(dft.format(vo.getVehicle_access_rate())+"%\t");
					//"车辆上线率："
					stb.append(dft.format(vo.getVehicle_online_rate())+"%\t");
					//"在岗率："
					stb.append(dft.format(vo.getReply_rate())+"%\t");
					//"轨迹完整率："
					stb.append(dft.format(vo.getTrack_complete_rate())+"%\t");
					//"数据合格率："
					int trackNum = vo.getTrack_normal()+vo.getException_track_count();
					stb.append((trackNum <= 0 ? 0.00 :dft.format(vo.getTrack_normal()/trackNum))+"%\n");
				}
			}
		}
		return stb.toString();
	}

}
